var loading = false;

jQuery(document).ready(function() {
	jQuery.cleditor.defaultOptions.width = 587;
	jQuery.cleditor.defaultOptions.height = 200;
	jQuery.cleditor.defaultOptions.controls = "bold italic underline";
	jQuery(".edit_entry textarea[name=body]").cleditor();

	bindEntryUploadForm();
	bindEntryForm();
	
	jQuery("#avatarFileEntry").change(function(){
		jQuery("#txtFileNameEntry").val(jQuery(this).val());
	});
});

function updateImagePath(responseText, statusText, xhr, $form) {
	var image = jQuery('image', responseText).text();
	rel = $form.attr("rel");
	jQuery("input[name='imgURL'][rel=" + rel + "]").val(image);
	jQuery("img[id^='preview_'][rel=" + rel + "]").attr("src", image).show();
	if (image != null && image != "") {
		jQuery("img[id^='preview_'][rel=" + rel + "]").parent().show();
	} else {
		jQuery("img[id^='preview_'][rel=" + rel + "]").parent().hide();
	}
	loading = false;
	jQuery("#txtFileNameEntry").iUnblock();
}

function validateImageUpload(formData, jqForm, options) {
	var form = jqForm[0];
	if (form.image.value) {
		jQuery("#txtFileNameEntry").iBlock({img: '/images/ajaxloading.gif'});
		return true;
	}
	
	iAlert("Bạn chưa chọn hình ảnh để upload");
	return false;
}

function validateEntry(title, body) {
	if (title && body) {
		return true;
	}
	
	alert("entry error");
	return false;
}

function bindEntryUploadForm() {
	jQuery("form[id^='upload_form_'][rel^='edit_entry_']").ajaxForm({
		url : ctx+'/fileupload/file',
		type : 'post',
		dataType : 'xml',		
		beforeSubmit : validateImageUpload,
		success : updateImagePath
	});
	
	jQuery("a#uploadAvatarSubmitButton[rel^='edit_entry_']").unbind("click").click(function(){
		if(loading == true){
			return false;
		}
		rel = jQuery(this).attr("rel");		
		jQuery("form[id^='upload_form_'][rel^='" + rel + "']").submit();
		return false;
	});
}

function bindEntryForm() {
	$form = jQuery("form[id^='entry_form_'][rel^='edit_entry_']");
	
	jQuery("a[id^='save_entry_']").click(function() {
		rel = jQuery(this).attr("rel");
		title = jQuery(".titlebox[rel=" + rel + "]").val();
		body = jQuery(".infobox[rel=" + rel + "]").val();
		if (validateEntry(title, body)) {
			$form.submit();
		}
	});
	
	jQuery("a[id^='delete_entry_']").click(function() {
		window.location.href = "/dashboard.html";
	});
}
